import cfg
import mail

import base64
import random
import time

def encode(s):
	return base64.b16encode(s)

def decode(s):
	return base64.b16decode(s)

def get_pw(user,realm):
	section = user+'@'+realm
	raw = cfg.get('cred',section,'pw','')
	return decode(raw)

def set_pw(user,realm,pw):
	section = user+'@'+realm
	encoded = encode(pw)
	cfg.set('cred',section,'pw',encoded)
	ts = time.strftime('%Y%m%d%H%M%S')
	cfg.set('cred',section,'set',ts)
	cfg.set('cred',section,'user',user)
	cfg.set('cred',section,'realm',realm)

def set_email(user,email):
	cfg.set('cred','email',user,email)

def get_email(user):
	return cfg.get('cred','email',user,'')

def email_password(user,realm="rivulet"):
	email=get_email(user)
	if not email:
		print "No email address for user",user
		return
	pw=get_pw(user,realm)
	url = cfg.get('cfg','meta','url','')
	env = cfg.get('cfg','meta','name','default')
	if url:
		env_str = '<a href="%s">%s</a>' % (url,env)
	else:
		env_str = env
	sub="rivulet password notification"
	body="""<br>
	<b>environment:</b><br>%s<br><br>
	<b>realm:</b><br>%s<br><br>
	<b>user:</b><br>%s<br><br>
	<b>password:</b><br>%s<br><br>
	""" % (env_str,realm,user,pw)
	mail.send(email,sub,body,sender=email)

def get(user,realm,key,default=''):
	section = user+'@'+realm
	raw = cfg.get('cred',section,key,default)
	return raw

def action_auth(user,action,tags):
	roles = get(user,'rivulet','roles').split()
	if 'all_all' in roles:
		return True
	if action+'_all' in roles:
		return True
	for t in tags:
		if 'all_'+t in roles:
			return True
		if action+'_'+t in roles:
			return True
	return False

def random_pw(length=8):
	return ''.join(random.sample("abcdef1234567890",length))

def get_owners_emails(tag_list):
	out = set()
	tag_set=set(['all_'+t for t in tag_list])
	sections = [s for s in cfg.sections('cred') if s.endswith('@rivulet')]
	for s in sections:
		roles = set(cfg.get('cred',s,'roles','').split())
		if tag_set.intersection(roles):
			email = get_email(s[:-len("@rivulet")])
			if email:
				out.add(email)
	return list(out)

if __name__=="__main__":
	print get_owners_emails(["zcx"])
